// pages/goods_detail/goods_detail.js
const app = getApp()
const Host = require('../../config').Host
var WxParse = require('../../wxParse/wxParse.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        successShow: false,
        bannerList: [],
        autoplay: true,
        interval: 2500,
        swiperCurrent: 0,
        mengShow: false,
        tanShow: false,
        countChoosed:false,
        count: 1, //初始选择商品的数量
        standardIndex: -1, //初始选择规格的下标
        goods: {},
        identification: [
            '企业认证', '店铺认证', '担保交易'
        ],
        tab: ['商品详情', '用户评价'],
        tabIndex: 0,
        commentIndex: 0,
        comment_list: [],
        kefu_message: 0,
        cart_message: 0,
        actionSheetHidden: true,
        canvasHidden: true,
        post_code: '',
        code_word: '扫描或长按小程序码',
        screenWidth: 0,
        canvasImg: '',
        is_login: false, //是否登录
        phone: '',
        real_code: '123456', //初始正确的验证码
        code: '',
        sendStart: false, //是否开始发送验证码
        time: 60, //倒计时
        bindShow: false,
        smsId: 0,
    },

    getPhone: function (e) {
        this.setData({
            phone: e.detail.value,
        })
    },
    getCode: function (e) {
        this.setData({
            code: e.detail.value,
        })
    },
    sendCode: function () {
        var that = this;
        var reg = new RegExp(/^1(3|4|5|7|8|9)\d{9}$/);
        if (!reg.exec(that.data.phone)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none',
            })
        } else {
            that.setData({
                sendStart: true,
            })
            function move() {
                var timer = setInterval(() => {
                    var time = that.data.time;
                    time--;
                    that.setData({
                        time: time,
                    })
                    if (time < 0) {
                        clearInterval(timer);
                        that.setData({
                            time: 60,
                            sendStart: false,
                        })
                    }
                }, 1000)
            }
            move();

            var phone = that.data.phone;
            wx.request({
                url: Host + 'Mine/sendverify',
                data: { phone },
                success: function (res) {
                    //console.log(res.data);
                    if (res.data.code == 400) {
                        wx.showModal({
                            title: '提示',
                            content: '验证码发送失败',
                            showCancel: false,
                        })
                    } else {
                        wx.showModal({
                            title: '提示',
                            content: '验证码发送成功，请注意查看',
                            showCancel: false,
                        })
                        that.setData({
                          real_code: res.data.result,
                          smsId: res.data.smsId
                        })
                    }
                },
            })
        }
    },
    login: function () {
        var that = this;
        var reg = new RegExp(/^1(3|4|5|7|8|9)\d{9}$/);
        if (!that.data.phone) {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none',
            })
        } else if (!reg.exec(that.data.phone)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none',
            })
        } else if (that.data.code != that.data.real_code) {
            wx.showToast({
                title: '请输入正确的验证码',
                icon: 'none',
            })
        } else {
            var phone = that.data.phone;
            var openid = wx.getStorageSync('openid');
            var smsId = that.data.smsId;
            wx.request({
                url: Host + 'Mine/bindphone',
                data: { openid, phone, smsId },
                method: 'post',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                success: function (res) {
                    if (res.data.code == 200) {
                        that.setData({
                            is_login: true,
                            mengShow: false,
                            bindShow: false,
                        })
                        wx.showToast({
                            title: '登录成功',
                            icon: 'success',
                        })
                        // setTimeout(function () {
                        //     wx.switchTab({
                        //         url: '/pages/index2/index2',
                        //     })
                        // }, 1000)
                    } else {
                        wx.showToast({
                            title: res.data.errmsg,
                            icon: 'none',
                        })
                    }
                },
            })
        }
    },
    swiperChange: function(e) {
        // console.log(e);
        this.setData({
            swiperCurrent: e.detail.current //获取当前轮播图片的下标
        })
    },
    full: function(e) {
        var that = this;
        var url = e.currentTarget.dataset.url;
        wx.previewImage({
            current: url, // 当前显示图片的http链接
            urls: that.data.bannerList // 需要预览的图片http链接列表
        })
    },
    chooseTabIndex: function(e) {
        var index = e.currentTarget.id;
        this.setData({
            tabIndex: index,
        })
    },
    loadMore: function() {
        var that = this;
        var comment_list = that.data.comment_list;
        var data = [{
            id: '0',
            img: 'http://www.meiliancheng.cn/public/meiliancheng/imagezy/zst/banner.png',
            name: '刘大帅',
            date_time: '2018-08-29  14:51:23',
            word: '商品好好商品好好商品好好商品好好商品好好商品好商品好好商品好好商品好好商品好好商品好好',
            imgList: [],
            reply: '',
        }, ];
        var list = comment_list.concat(data);
        that.setData({
            comment_list: list,
        })
    },
    //获取评论内容下标
    getIndex: function(e) {
        var index = e.currentTarget.id;
        this.setData({
            commentIndex: index,
        })
    },
    //放大图片
    full2: function(e) {
        var that = this;
        var url = e.currentTarget.dataset.url;
        wx.previewImage({
            current: url, // 当前显示图片的http链接
            urls: that.data.comment_list[that.data.commentIndex].imgList // 需要预览的图片http链接列表
        })
    },
    // 选择规格
    chooseStandardIndex: function(e) {
        var index = e.currentTarget.id;
        this.setData({
            standardIndex: index,
        })
    },
    getCount: function(e) {
        this.setData({
            count: e.detail.value,
        })
    },
    del: function() {
        var that = this;
        var count = that.data.count;
        count--;
        if (count < 1) {
            count = 1;
            wx.showToast({
                title: '至少选择一个商品',
                icon: 'none',
            })
        }
        that.setData({
            count: count,
        })
    },
    add: function() {
        var that = this;
        var count = that.data.count;
        count++;
        that.setData({
            count: count,
        })
    },
    closeShow: function() {
        this.close();
    },
    close: function() {
        var that = this;
        that.setData({
            mengShow: false,
            tanShow: false,
            count: 1,
            standardIndex: -1,
            canvasHidden: true,
            bindShow:false,
        })
    },
  sure2: function () {
    var that = this;
    var openid = wx.getStorageSync('openid');
    var goods = that.data.goods;
    var standardIndex = that.data.standardIndex;
    if (that.data.standardIndex == -1 && goods.standard.length > 0) {
      wx.showToast({
        title: '您还没有选择规格',
        icon: 'none',
      })
    } else {
      var arr = [];
      var obj = {};
      obj.goods_id = goods.id;
      obj.standard_id = standardIndex > -1 ? goods.standard[standardIndex].id : 0;
      obj.goods_count = that.data.count;
      arr.push(obj);
      obj = null;
      //console.log(arr)
      that.setData({
        mengShow: false,
        tanShow: false,
        standardIndex: -1,
        count: 1,
      })
      if (that.data.type === "cart") {
        wx.request({
          url: Host + 'Default/addcart',
          data: { openid, item: JSON.stringify(arr) },
          method: 'post',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: function (res) {
            if (res.data.code == 200) {
              var cart_message = that.data.cart_message;
              cart_message++;
              that.setData({
                cart_message: cart_message
              })
              wx.showToast({
                title: '加入购物车成功',
                icon: 'success',
              })
            } else {
              wx.showToast({
                title: res.data.errmsg,
                icon: 'none',
              })
            }
          },
        })
      } else {
        wx.setStorageSync('order', arr)
        wx.navigateTo({
          url: '/pages/order/order',
        })
      }
    }

  },
    openShow: function (e) {
        var that = this;
        if (!that.data.is_login) {
            that.setData({
                bindShow: true,
                mengShow: true,
            })
        } else {
            var type = e.currentTarget.dataset.type;
            that.setData({
                mengShow: true,
                tanShow: true,
                type: type,
            })
        }
    },
    // addCart: function() {
    //   var that = this;
    //   var standardIndex = that.data.standardIndex;
    //   var openid = wx.getStorageSync('openid');
    //     if (that.data.standardIndex == -1 && that.data.countChoosed==false) {
    //         that.setData({
    //             mengShow: true,
    //             tanShow: true,
    //         })
            
    //     } else {
    //         var goods = that.data.goods;
    //         var standardIndex = that.data.standardIndex;
    //         var arr = [];
    //         var obj = {};
    //         obj.goods_id = goods.id;
    //         obj.standard_id = standardIndex > -1 ? goods.standard[standardIndex].id : '-1';
    //         obj.goods_count = that.data.count;
    //         arr.push(obj);
    //         obj = null;
    //         console.log(arr)
    //         var cart_message = that.data.cart_message;
    //         cart_message++;
    //         wx.showToast({
    //             title: '加入购物车成功',
    //             icon: 'success',
    //         })
    //         that.setData({
    //             standardIndex: -1,
    //             count:1,
    //             countChoosed:false,
    //             cart_message: cart_message
    //         })
    //     }
    // },
    // onceBuy: function() {
    //     var that = this;
    //     var standardIndex = that.data.standardIndex;
    //     if (that.data.standardIndex == -1 && that.data.countChoosed == false){
    //         that.setData({
    //             mengShow: true,
    //             tanShow: true,
    //         })
    //     }else{
    //         var goods = that.data.goods;
    //         var standardIndex = that.data.standardIndex;
    //         var arr = [];
    //         var obj = {};
    //         obj.goods_id = goods.id;
    //         obj.standard_id = standardIndex > -1 ? goods.standard[standardIndex].id : '-1';
    //         obj.goods_count = that.data.count;
    //         arr.push(obj);
    //         obj = null;
    //         console.log(arr)
    //         that.setData({
    //             standardIndex: -1,
    //             count: 1,
    //             countChoosed: false,
    //         })
    //         // wx.navigateTo({
    //         //     url: '/pages/order/order',
    //         // })
    //     }
    // },
    share: function() {
        var that = this;
        that.setData({
            actionSheetHidden: false,
        })

    },
    listenerActionSheet: function() {
        this.setData({
            actionSheetHidden: !this.data.actionSheetHidden
        })
    },
    listenerButton: function() {
        this.setData({
            actionSheetHidden: !this.data.actionSheetHidden
        });
    },
    listenerItem: function() {
        var that = this;
        that.setData({
            actionSheetHidden: !this.data.actionSheetHidden,
            canvasHidden: false,
            mengShow: true,
        });
    },
    //保存到相册
    savePoster: function() {
        var that = this;
        setTimeout(function() {
            wx.canvasToTempFilePath({
                canvasId: 'poster',
                fileType: 'jpg',
                success: function(res) {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success(res) {
                            that.setData({
                                mengShow: false,
                                canvasHidden: true,
                            })
                            wx.showToast({
                                title: '保存成功',
                            });
                        },
                        fail() {
                            wx.hideLoading()
                        }
                    })
                }
            })
        }, 500);
    },
    cancelPoster: function() {
        this.setData({
            mengShow: false,
            canvasHidden: true,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
      var that=this;
      that.setData({
        goods_id:options.id
      })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        var that = this;
        //获取绑定信息
        var openid = wx.getStorageSync('openid');
        wx.request({
            url: Host + 'Mine/personal',
            data: { openid },
            method: 'post',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            success: function (res) {
                that.setData({
                    is_login: res.data.is_bind,
                });
            },
        })

      var id = that.data.goods_id;
      wx.request({
        url: Host + 'Default/goodsDetail',
        data: { openid, id},
        success: function (res) {
          if (res.data.code==200) {
            that.setData({
              goods: res.data.goods,
              bannerList: res.data.goods.banner,
              post_code: res.data.goods.post_code,
              comment_list: res.data.goods.comment_list,
              cart_message: res.data.goods.shopcartnum
            });
            WxParse.wxParse('content', 'html', res.data.goods.goods_details, that, 5)
            if (that.data.goods && that.data.bannerList) {
              that.setData({
                successShow: true,
              })
            }
            wx.getSystemInfo({ //获取屏幕宽度
              success: function (res5) {
                that.setData({
                  screenWidth: res5.screenWidth,
                })
                wx.getImageInfo({
                  src: that.data.goods.img,
                  success: function (res1) {
                    that.setData({
                      good_img: res1.path,
                    })
                    wx.getImageInfo({
                      src: that.data.post_code,
                      success: function (res2) {
                        that.setData({
                          post_code: res2.path,
                        })
                        const ctx = wx.createCanvasContext('poster');
                        ctx.clearRect(0, 0, 0, 0);
                          const width1 = 470 / 750 * that.data.screenWidth;
                        const height1 = 376 / 750 * that.data.screenWidth;
                          console.log(res1.width,res1.height)
                        ctx.drawImage(that.data.good_img, 257 / 750 * that.data.screenWidth - width1 / 2, 62 / 750 * that.data.screenWidth, width1, height1);
                        ctx.restore(); //绘制商品图片
                        function textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
                          let strLength = 0;
                          let rows = 1;
                          let str = 0;
                          let arrText = []; //用来装入海报文字
                          for (let j = 0; j < text.length; j++) {
                            if (text.charCodeAt(j) > 255) {
                              strLength += 2;
                            } else {
                              strLength++;
                            }
                            if (strLength > rows * num) {
                              strLength++;
                              arrText.push(text.slice(str, j));
                              str = j;
                              rows++;
                            }
                          }
                          arrText.push(text.slice(str, text.length));
                          return [strLength, arrText, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
                        }
                        const num = 26; // 正文单行显示字符长度 最多一行显示20个汉字多了就换行
                        const lineHeight = 40 / 750 * that.data.screenWidth;
                        let [strLength, arrText, rows] = textByteLength(that.data.goods.title, num);
                        console.log(strLength, arrText, rows)
                        ctx.setFontSize(30 / 750 * that.data.screenWidth);
                        if (arrText.length > 2) {
                          arrText.splice(2);
                          arrText[1] = arrText[1].concat('...');
                        }
                        for (let a = 0; a < arrText.length; a++) {
                          console.log(arrText[a])
                          ctx.fillText(arrText[a], 22 / 750 * that.data.screenWidth, 580 / 750 * that.data.screenWidth + lineHeight * a);
                        }
                        ctx.restore(); //商品名称
                        //var arrtext2 = that.data.goods.standard[0].price + '-' + that.data.goods.standard[that.data.goods.standard.length - 1].price;
                        var arrtext2 = that.data.goods.price;
                        ctx.setFontSize(36 / 750 * that.data.screenWidth);
                        ctx.setFillStyle('#ff4444'); //价格文字
                        ctx.fillText(arrtext2, 42 / 750 * that.data.screenWidth, 772 / 750 * that.data.screenWidth);
                        ctx.setFontSize(20 / 750 * that.data.screenWidth);
                        ctx.fillText('￥', 22 / 750 * that.data.screenWidth, 772 / 750 * that.data.screenWidth);
                        ctx.setFillStyle('#bcbcbc');
                        ctx.setFontSize(16 / 750 * that.data.screenWidth);
                        ctx.fillText(that.data.code_word, 332 / 750 * that.data.screenWidth, 847 / 750 * that.data.screenWidth);
                        let r = 60 / 750 * that.data.screenWidth;
                        let d = 2 * r;
                        let cx = 400 / 750 * that.data.screenWidth;
                        let cy = 700 / 750 * that.data.screenWidth + r;
                        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
                        ctx.clip();
                        ctx.drawImage(that.data.post_code, cx - r, cy - r, d, d);
                        wx.createSelectorQuery().select('#poster').boundingClientRect().exec(function (res) {
                          that.setData({
                            canvasWidth: res[0].width,
                            canvasHeight: res[0].height,
                          })
                        });
                        ctx.draw(false, function () {
                          wx.canvasToTempFilePath({
                            x: 0,
                            y: that.data.canvasHeight,
                            width: that.data.canvasWidth,
                            height: that.data.canvasHeight,
                            destWidth: that.data.canvasWidth,
                            destHeight: that.data.canvasHeight,
                            fileType: 'jpg',
                            canvasId: 'poster',
                            success(res) {
                              console.log(res.tempFilePath)
                              that.setData({
                                canvasImg: res.tempFilePath,
                              })
                            },
                            fail: function (res) {
                              console.log(res);
                            },
                          })

                        });

                      }
                    })
                  }
                })
              },
            })
          } else {
            wx.showToast({
              title: res.data.errmsg,
              icon: 'none',
            })
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              })
            }, 1000)
          }
        },
      })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
      var that = this
      var goodsid = that.data.goods_id

      if (!goodsid) {
        wx.showModal({
          title: '提示',
          content: '转发失败',
          showCancel: false,
        })
        return false
      }

      var title = that.data.goods.sharename;
      var imageUrl = that.data.goods.shareimg;
      wx.showShareMenu({
        withShareTicket: true
      })
      //console.log(imageUrl);
      return {
        title: title,
        path: '/pages/goods_detail/goods_detail?id=' + goodsid,
        imageUrl: imageUrl,
        success: function (res) {
          //console.log(res)
          // 转发成功
        },
        fail: function (res) {
          // 转发失败
        }
      }

    }
})